<template>
  <div>
    <el-card>
      <CommonForm />
    </el-card>
    <el-card>
      <NavTab />
    </el-card>
    <el-card>
      <div class="budget-content">
        <el-form ref="form" :inline="true" label-width="130px" :model="form">
          <el-form-item label="设备编号：">
            <el-input v-model="form.EQUIPMENT_ID" />
          </el-form-item>
          <el-form-item label="设备类型：">
            <el-input v-model="form.EQUIPMENT_TYPE" />
          </el-form-item>
          <el-form-item>
            <el-button @click="reset">
              <vui-icon icon="refresh-line" />
              重置
            </el-button>
            <el-button type="primary" @click="search">
              <vui-icon icon="search-line" />
              查询
            </el-button>
          </el-form-item>
          <el-form-item>
            <div class="btns">
              <el-button type="primary" @click="newUpload">
                <vui-icon icon="upload-line" />
                导入外购价格表
              </el-button>
              <el-button
                :disabled="list.length == 0"
                style="margin-left: 10px"
                :type="StatusName == '发布数据' ? 'primary' : 'danger'"
                @click="dataRelease(StatusName)"
              >
                <vui-icon icon="save-line" />
                {{ StatusName }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <el-table border :data="list" highlight-current-row :max-height="500">
          <el-table-column label="设备编号" prop="EQUIPMENT_ID" />
          <el-table-column label="设备类型" prop="EQUIPMENT_TYPE" />
          <el-table-column label="数量" prop="QTY" />
          <el-table-column label="外购单价">
            <template #default="scope">
              <span>{{ Math.floor(scope.row.WHOLE_PRICE * 100) / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="外购费用">
            <template #default="scope">
              <span>{{ Math.floor(scope.row.TOTAL_TAX_EXCLUDEPRICE * 100) / 100 }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-dialog v-model="uploadVisible" title="外购价格上传" width="80%" @close="cancel">
      <div v-if="uploadVisible">
        <el-steps :active="active" align-center>
          <el-step title="上传模版数据" />
          <el-step title="模版数据检测" />
          <el-step title="单据建立完成" />
        </el-steps>
        <div class="step-two">
          <div v-if="active == 1">
            <div class="hint_">
              <p class="hint-title">特别提示</p>
              <p class="hint-explain">请使用系统要求模板按格式要求填写数据，填写完成进行数据上传</p>
            </div>
            <div class="box_">
              <div class="left-box"></div>
              <div>
                <p>填写导入数据信息</p>
                <p>请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除</p>
                <el-button type="text" @click="download">下载模板</el-button>
              </div>
            </div>
            <div class="box_">
              <div class="left-box"></div>
              <vui-upload
                ref="fileUploadRef"
                class="text-left"
                :file-name="uploadOptions.name"
                :limit="1"
                :post-data="uploadOptions.postData"
                :url="uploadOptions.url"
                @uploadSuccess="uploadSuccess"
              >
                <div>
                  <p>上传填好的信息表</p>
                  <p>文件后缀名必须为xls或xlsx(既Excel格式)，文件大小不得大于10M</p>
                  <el-button v-if="!file" size="small" type="text">上传文件</el-button>
                </div>
              </vui-upload>
            </div>
            <div class="footer_">
              <el-button type="primary" @click="clickUpload">下一步</el-button>
            </div>
          </div>
          <div v-if="active == 2">
            <div v-if="abnormal">
              <div class="box_" style="height: 80px">
                <div class="left-box"></div>
                <div>
                  <p>正常数量条数：{{ errorData.successNumber }}</p>
                  <p>
                    异常数量条数：
                    <span style="color: red">{{ errorData.failNumber }}</span>
                  </p>
                </div>
              </div>
              <div class="abnormal-hint">
                <p>异常提示</p>
                <template v-for="(item, index) in errorData.errorInfoList" :key="index">
                  <p style="color: red">
                    {{ item }}
                  </p>
                </template>
              </div>
            </div>
          </div>
          <div v-if="active == 3">
            <div>
              <p>数据导入成功</p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CommonForm from '@bqms/components/ComTable.vue'
  import NavTab from '../../components/NavTab.vue'
  import requestMethod from '../../common/requestMethod'
  import publicFn from '../../common/requestCommon'
  import { GFCD } from '@/utils/utils'
  import { download } from '../../api/home'
  const configSetting = GFCD('bqms')
  export default {
    name: 'OutsourcingCost',
    components: {
      CommonForm,
      NavTab,
    },
    data() {
      return {
        active: 1,
        uploadOptions: {
          postData: {
            method: requestMethod.OUTSOURCING_PRICE_IMPORT,
            data: '{"TEMP_TYPE":"OUT_PRICE_SOURCE"}',
          },
          name: 'uploadFile',
          url: `${configSetting.domain}${configSetting.baseUrl}`,
        },
        list: [],
        form: {},
        uploadVisible: false,
        errorData: {},
        abnormal: false,
        StatusName: '',
        formEnd: {},
      }
    },
    activated() {
      if (this.$store.getters['bqmsData/HeaderTable']['OUT_SOURCE_ISSUE'] == 'Y') {
        this.StatusName = '撤销发布'
      } else {
        this.StatusName = '发布数据'
      }
    },
    methods: {
      clickUpload() {
        if (this.$refs['fileUploadRef'].allImgNum) {
          this.$refs['fileUploadRef'].submitUpload()
        } else {
          this.$message({
            type: 'error',
            message: '请选择文件',
          })
        }
      },
      dataRelease() {
        if (this.$store.getters['bqmsData/HeaderTable']['OUT_SOURCE_ISSUE'] == 'Y') {
          this.$confirm('是否撤销发布？', '撤销发布', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(async () => {
              let res = await publicFn(requestMethod.REVERSE_RELESE, {
                TYPE: 'OUT_SOURCE_ISSUE',
                DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
              })
              if (res.code === '00000') {
                this.$message({
                  type: 'success',
                  message: '撤销发布成功!',
                })
                this.$pub(`topFormData`, true)
                // if (this.$store.getters['bqmsData/HeaderTable']['OUT_SOURCE_ISSUE'] == 'Y') {
                //   this.StatusName = '撤销发布'
                // } else {
                this.StatusName = '发布数据'
                // }
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg,
                })
              }
            })
            .catch((e) => {
              console.log(e)
            })
        } else {
          this.$confirm('是否确认发布？', '数据发布成功', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(async () => {
              let res = await publicFn(requestMethod.DATA_RELEASE, {
                TYPE: 'OUT_SOURCE_ISSUE',
                DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
              })
              if (res.code === '00000') {
                this.$message({
                  type: 'success',
                  message: '发布成功!',
                })
                this.$pub(`topFormData`, true)
                // if (this.$store.getters['bqmsData/HeaderTable']['OUT_SOURCE_ISSUE'] == 'Y') {
                this.StatusName = '撤销发布'
                // } else {
                //   this.StatusName = '发布数据'
                // }
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg,
                })
              }
            })
            .catch((e) => {
              console.log(e)
            })
        }
      },
      reset() {
        this.form = {}
        this.getCostList()
      },
      newUpload() {
        this.active = 1
        this.errorData = {}
        this.uploadVisible = true
      },
      cancel() {
        this.getCostList()
      },
      async download() {
        let res = await download(`${configSetting.domain}${configSetting.baseUrl}`, {
          method: requestMethod.TEMPLATE_DOWNLOAD,
          data: JSON.stringify({ TEMP_TYPE: 'OUT_PRICE_SOURCE' }),
        })
        let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        let reader = new FileReader()
        reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = '外购价格模板.xlsx'
          a.href = e.target.result
          a.click()
        }
      },
      async threeNext() {
        let res = await publicFn(requestMethod.OUTSOURCING_SP_IMPORT, {
          ...this.formEnd,
          ACTION: 'OUT_SOURCE',
          DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
        })
        if (res.code === '00000') {
          this.active++
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      uploadSuccess(file) {
        let res = file.fileList[0].response
        console.log(res)
        if (res.code === '00000') {
          this.formEnd.FILE_PATH = res.data.filePath
          this.formEnd.FILE_NAME = res.data.fileName
          this.formEnd.FILE_HIS_NAME = res.data.originalFileName
          this.active++
          this.abnormal = false
          this.threeNext()
        } else if (res.code === 'S0055') {
          this.errorData.successNumber = res.count
          this.errorData.failNumber = res.data.length
          this.errorData.errorInfoList = res.data
          this.$message({
            type: 'error',
            message: res.msg,
          })
          this.abnormal = true
          this.active++
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
          })
        }
      },
      search() {
        this.getCostList()
      },
      async getCostList() {
        let res = await publicFn(requestMethod.OUTSOURCING_PRICE_QUERY, {
          '#LIMIT#': 1,
          '#PAGE_SIZE#': 99999,
          OUT_SOURCE: 'Y',
          ...this.form,
          DOCNO: this.$store.getters['bqmsData/budgetSheetNum'],
          // VERSION: this.$store.getters['bqmsData/HeaderTable'].VERSION,
        })
        if (res.code === '00000') {
          this.list = res.data[requestMethod.OUTSOURCING_PRICE_QUERY].data
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
    },
    //this.$pub(`topFormData`, true)发布时调用
  }
</script>
<style lang="scss" scoped>
  .footer_ {
    margin-top: 20px;
    text-align: center;
  }
  .flex_ {
    display: flex;
    justify-content: space-between;
  }
  .el-select .el-input .el-input__inner {
    width: 193px !important;
  }
  .hint_ {
    background: #fff5e6;
    padding: 15px 30px;
    box-sizing: border-box;
    .hint-title {
      font-weight: 600;
    }
    .hint-explain {
      margin-top: 10px;
    }
  }
  .step-two {
    margin-top: 20px;
  }
  .box_ {
    margin-top: 20px;
    display: flex;
    align-items: center;
    height: 115px;
    border: 1px solid #d8d3d3;
    p {
      margin-top: 10px;
    }
  }
  .left-box {
    background: #f5f5f5;
    width: 50px;
    height: 100%;
  }
  .abnormal-hint {
    padding: 15px;
    margin-top: 20px;
    box-sizing: border-box;
    border: 1px solid #f5f5f5;
    p {
      margin-top: 10px;
    }
  }
  .success {
    display: flex;
    justify-content: center;
    align-items: center;
    & > div {
      height: 300px;
    }
  }
</style>
